import { EllipsisOutlined, PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable, TableDropdown } from '@ant-design/pro-components';
import {Button, Dropdown, Image, message} from 'antd';
import { useRef } from 'react';
import {getAllUser, updateUser,deleteUser__} from '@/services/ant-design-pro/api'
export const waitTimePromise = async (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

export const waitTime = async (time: number = 100) => {
  await waitTimePromise(time);
};


const columns: ProColumns<API.CurrentUser>[] = [
  {

    dataIndex: 'id',
    valueType: 'indexBorder',
    width: 48,
  },
  {
    title: '用户账号',
    dataIndex: 'userAccount',
  },
  {
    title: '用户名',
    dataIndex: 'username',
  },
  {
    title: '用户头像',
    dataIndex: 'avatarUrl',
    search: false,
    render: (_, record) => (
      // <Image src={avatarUrl} />
      <Image src={record.avatarUrl} width={50}/>
    ),
  },
  {
    title: '更新时间',
    dataIndex: 'updatetime',
    valueType: 'dateTime',
    sorter: true,
    hideInSearch: true,
  },
  {
    title: '操作',
    valueType: 'option',
    key: 'option',
    render: (text, record, _, action) => [
      <a
        key="editable"
        onClick={() => {
          // @ts-ignore
          action?.startEditable?.(record.id)
        }}
      >
        编辑
      </a>,
      <TableDropdown
        key="actionGroup"
        onSelect={() => action?.reload()}
        menus={[
          { key: 'copy', name: '复制' },
          { key: 'delete', name: '删除' },
        ]}
      />,
    ],
  },
];



export default () => {
  const actionRef = useRef<ActionType>();

  return (
    <ProTable<API.CurrentUser>
      columns={columns}
      actionRef={actionRef}
      cardBordered
      // @ts-ignore
      request={async (params, sort, filter) => {
        console.log(sort, filter);
        const userList = await getAllUser();
        return {
          data:userList
        };
      }}
      editable={{
        type: 'multiple',
        onSave: async (key,record)=> {
          const userAcc = record.userAccount;
          const username = record.username;
          const avatarUrl = record.avatarUrl;
          const updateTime = record.updatetime;
          const upUser: API.CurrentUser = {
            userAccount: userAcc,
            username: username,
            avatarUrl: avatarUrl,
            updatetime: updateTime,
          }
          const flag = await updateUser(upUser);
          if(!flag){
            message.error("更新失败！");
          }
          else{
            message.success("更新成功！")
          }
      },
        onDelete: async (key,record) =>{
            const id = record.id;
            console.log(id)
            // @ts-ignore
          const flag = await deleteUser__(id);
          if(!flag){
            message.error("删除用户失败");
          }
          else{
            message.success("成功删除用户");
          }
        }

      }}
      columnsState={{
        persistenceKey: 'pro-table-singe-demos',
        persistenceType: 'localStorage',
        defaultValue: {
          option: { fixed: 'right', disable: true },
        },
        onChange(value) {
          console.log('value: ', value);
        },
      }}
      rowKey="id"
      search={{
        labelWidth: 'auto',
      }}
      options={{
        setting: {
        },
      }}
      form={{
        // 由于配置了 transform，提交的参数与定义的不同这里需要转化一下
        syncToUrl: (values, type) => {
          if (type === 'get') {
            return {
              ...values,
              created_at: [values.startTime, values.endTime],
            };
          }
          return values;
        },
      }}
      pagination={{
        pageSize: 5,
        onChange: (page) => console.log(page),
      }}
      dateFormatter="string"
      headerTitle="用户列表"
      toolBarRender={() => [
        <Button
          key="button"
          icon={<PlusOutlined />}
          onClick={() => {
            actionRef.current?.reload();
          }}
          type="primary"
        >
          新建
        </Button>,
        <Dropdown
          key="menu"
          menu={{
            items: [
              {
                label: '1st item',
                key: '1',
              },
              {
                label: '2nd item',
                key: '2',
              },
              {
                label: '3rd item',
                key: '3',
              },
            ],
          }}
        >
          <Button>
            <EllipsisOutlined />
          </Button>
        </Dropdown>,
      ]}
    />
  );
};
